import { ref } from 'vue'
import SockJS from 'sockjs-client'
import { CompatClient, Stomp } from '@stomp/stompjs'
import { useMessageStore } from '@/stores/app'

const stompClient = ref<CompatClient | null>(null)
const connected = ref(false)

export function useStompClient() {
  const messageStore = useMessageStore()

  // 建立连接
  function connect(userId: number) {
    return new Promise<void>((resolve, reject) => {
      if (connected.value) {
        resolve()
        return
      }

      const socket = new SockJS(`http://localhost:8080/ws?userId=${userId}`)
      const client = Stomp.over(socket)
      client.debug = () => {} // 可选：关闭调试日志

      client.connect({}, () => {
        stompClient.value = client
        connected.value = true

        // ✅ 私聊订阅
        const privatePath = '/user/queue/messages'
        console.log(`✅ 已订阅私聊路径：${privatePath}`)
        client.subscribe(privatePath, (msg) => {
          try {
            const message = JSON.parse(msg.body)
            console.log('📩 收到私聊：', message)
            messageStore.saveMessage(message)
          } catch (e) {
            console.error('❌ 解析私聊消息失败:', e)
          }
        })

        resolve()
      }, (err) => {
        console.error('❌ STOMP 连接失败:', err)
        reject(err)
      })
    })
  }

  // 订阅群组
  function subscribeGroup(groupId: number) {
    if (!stompClient.value || !connected.value) {
      console.warn('⚠️ STOMP 未连接，无法订阅群组')
      return
    }

    const destination = `/topic/group.${groupId}`
    console.log(`✅ 已订阅群组路径：${destination}`)
    stompClient.value.subscribe(destination, (msg) => {
      try {
        const message = JSON.parse(msg.body)
        console.log(`📨 群组 [${groupId}] 收到消息：`, message)
        messageStore.saveMessage(message)
      } catch (e) {
        console.error('❌ 解析群组消息失败:', e)
      }
    })
  }

  return {
    connect,
    subscribeGroup,
    isConnected: connected,
  }
}
